﻿using IdentityModel;
using IdentityServer4.Test;
using IdentityServer4.Validation;
using IdentityServerHost.Quickstart.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IdentityServer4.Models;

namespace IdentityServer4API.Quickstart.APILogin
{
    /// <summary>
    /// 自定义API用户登录
    /// </summary>
    public class LoginValidator : IResourceOwnerPasswordValidator
    {
        private readonly TestUserStore _users;


        public LoginValidator(TestUserStore users = null)
        {
            _users = users ?? new TestUserStore(TestUsers.Users);
        }
        /// <summary>
        /// 登录用户校验
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            //获取验证码参数 自定义参数使用context.Request.Raw["code"] 方式获取
            var code = context.Request.Raw["code"];
            //校验用户信息 这里引入orm 查询数据库用户账号密码信息
            if (_users.ValidateCredentials(context.UserName, context.Password))
            {
                context.Result = new GrantValidationResult(
                 subject: context.UserName,
                 authenticationMethod: "custom",
                // claims: GetUserClaims(userObj.Data),用于存储登录用户信息，根据需求配置
                 identityProvider: "local"
              );
            }
            else
            {
                //验证失败
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "账号密码错误");
            }
            return Task.CompletedTask;
        }

        /// <summary>
        /// 可以根据需要设置相应的Claim
        /// </summary>
        /// <returns></returns>
        private Claim[] GetUserClaims(TestUser info)
        {
            return new Claim[]
            {
                new Claim("UserId",info.SubjectId.ToString()),
                new Claim(JwtClaimTypes.Name,info.Username),
                new Claim("userInfo",JsonConvert.SerializeObject(info)),
                new Claim(JwtClaimTypes.GivenName, "jaycewu"),
            };
        }

    }
}
